import Vue from 'vue';
import store from '@/store';
import constants from "../api/constants";
import { message } from '@common/assets/js/resetMessage.js'

let Base64 = require('js-base64').Base64;
const eachRoutes = routes => {
	let list = [];
	for (let item of routes) {
		if (utils.isNotEmptyList(item.children)) {
			let children = eachRoutes(item.children);
			if (utils.isNotEmptyList(children)) {
				list = list.concat(children);
			}
		} else {
			list.push(item);
		}
	}
	return list;
};
const getRoutePath = route => {
    const meta = route.meta;
    if (utils.isNotEmpty(meta.permissionPath)) {
        return meta.permissionPath;
    }
    return route.path;
};
const utils = {
	async procRouter(to, from, next, store, routes, skipLogin = false) {
        if (!store.state.version_map) {
            await store.dispatch('initVersionMap');
        }
        let data = store.getters.getMenuByPath(getRoutePath(to));
        // 检查版本
        const version = utils.getSessionStorage(store.state.storageName, 'ver');
        if (data.min_ver && version < data.min_ver) {
            message.error(`该功能属于${store.state.version_map[data.min_ver]}，请先升级版本再使用`);
            next(false);
            return false;
        }
        let title = utils.replaceTag(to);
        document.title = `${ title }` || window.configs.projectTitle;
		if (to.path === '/') {
			next('/login');
			return false;
		}
		let skipRoute = [ '/login', '/dashboard', '/redirect', '/reg', '/403', '/404', '/view_attach' ];
		if (skipRoute.indexOf(to.path) !== -1 || to.path.indexOf('/app') === 0) {
			next();
			return false;
		} else {
			const token = utils.getSessionStorage(store.state.storageName, 'accessToken');
			if (utils.isEmpty(token) && to.path !== '/login') {
				next('/login');
				return false;
			}

			let globalSetting = store.state.global_setting || {};
			if (utils.isNotEmpty(token) && utils.isEmpty(globalSetting.id)) {
				store.dispatch('initGlobalSetting');
			}
			let routeList = eachRoutes(routes);
			let filterRoute = routeList.filter(item => {
				if (item.path.indexOf('/:') !== -1) {
					let path = item.path.split('/:')[0] + '/';
					return to.path.indexOf(path) === 0;
				}
				return item.path === to.path;
			});
			if (!utils.isNotEmptyList(filterRoute)) {
				next('/404');
				return false;
			}
			let permission = store.state.permission[data.sid] || [];
			// 检查权限
			if (!utils.isNotEmpty(data.sid)) {
				next('/403');
				return false;
			}
			if (data.child_count > 0 && !utils.isNotEmptyList(permission)) {
				next('/403');
				return false;
			}
			to.meta.permission = permission;
			if (!skipLogin && !token && to.path !== '/login') {
				next('/login');
				return false;
			} else {
				// 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
				if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
					Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
						confirmButtonText: '确定'
					});
					return false;
				} else {
					return true;
				}
			}
		}
	},
	//返回账套sid
	getAccountSetSid() {
		return encodeURIComponent(utils.getLocalStorage(store.state.accountSetSid)) || '';
	},
	//返回以斜杠结尾的账套sid
	getAccountSetSidEndWithSlash() {
		return encodeURIComponent(utils.getLocalStorage(store.state.accountSetSid) || '') + '/';
	},
	getDownloadExcelTemplateUrl(sid) {
		return `${ window.configs.requestPrefix }${ constants.File_DownloadExcelTemplate }${ utils.getAccountSetSidEndWithSlash() }${ sid }`;
	},
    //判断指定路径是否是当前版本可以访问，如果不是，则提示
    isVersionAuthPath(to){
        let data = store.getters.getMenuByPath(to);
        // 检查版本
        const version = utils.getSessionStorage(store.state.storageName, 'ver');
        if (data.min_ver && version < data.min_ver) {
            message.error(`该功能属于${store.state.version_map[data.min_ver]}，请先升级版本再使用`);
            return false;
        }
        return true;
    },
    getFileUrl(sid) {
        return `${ window.configs.requestPrefix }${ constants.File_GetFile }${ utils.getAccountSetSidEndWithSlash() }${ sid }`;
    },
	isNotEmpty: (str) => {
		return str !== null && str !== undefined && String(str).length > 0;
	},
	isEmpty: (str) => {
		return !utils.isNotEmpty(str);
	},
	isNotEmptyList: list => {
		return list && list.length > 0;
	},
	getLocalStorage: (dbName, keyName, paramName) => {
		let storage = localStorage.getItem(dbName);
		if (!utils.isNotEmpty(storage)) {
			return null;
		}
		storage = JSON.parse(storage);
		if (!utils.isNotEmpty(keyName)) {
			return storage;
		}
		let params = storage[keyName];
		if (!utils.isNotEmpty(paramName)) {
			return params;
		}
		return params[paramName];
	},
	setLocalStorage: (dbName, data) => {
		localStorage.setItem(dbName, JSON.stringify(data));
	},
	removeLocalStorage: (dbName) => {
		localStorage.removeItem(dbName);
	},
	getSessionStorage: (dbName, keyName, paramName) => {
		let storage = sessionStorage.getItem(dbName);
		if (!utils.isNotEmpty(storage)) {
			return null;
		}
		storage = JSON.parse(storage);
		if (!utils.isNotEmpty(keyName)) {
			return storage;
		}
		let params = storage[keyName];
		if (!utils.isNotEmpty(paramName)) {
			return params;
		}
		return params[paramName];
	},
	setSessionStorage: (dbName, data) => {
		sessionStorage.setItem(dbName, JSON.stringify(data));
	},
	removeSessionStorage: (dbName) => {
		sessionStorage.removeItem(dbName);
	},
	logout: () => {
		store.commit('setUserInfo', {});
		store.commit('setGlobalSetting', {});
		store.commit('setApplication', '');
		utils.removeSessionStorage(store.state.storageName);
		utils.removeSessionStorage(store.state.tokenName);
	},
	/**
	 * 时间格式化
	 * @param date
	 * @param format
	 * @returns {string|*}
	 */
	formatDate: (date, format) => {
		if (!date) {
			return "";
		}
		if (typeof date == 'string' && date.indexOf('-') !== -1) {
			date = date.replace(/-/g, '/');
		}
		let thiz = new Date(date);
		let o = {
			"M+": thiz.getMonth() + 1,
			"d+": thiz.getDate(),
			"h+": thiz.getHours() % 12 === 0 ? 12 : thiz.getHours() % 12,
			"H+": thiz.getHours(),
			"m+": thiz.getMinutes(),
			"s+": thiz.getSeconds(),
			"q+": Math.floor((thiz.getMonth() + 3) / 3),
			"S": thiz.getMilliseconds()
		};
		if (/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (thiz.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (let k in o) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
			}
		}
		return format;
	},
	toFixed: (arg1, len) => {
		if (utils.isEmpty(arg1)) {
			arg1 = 0;
		}
		if (utils.isEmpty(len)) {
			len = 0;
		}
		try {
			return Number(arg1).toFixed(len);
		} catch (e) {
			throw new Error(e);
		}
	},
	/**
	 * 加法函数，用来得到精确的加法结果
	 * @param arg1
	 * @param arg2
	 * @returns {number}
	 */
	accAdd: (arg1, arg2) => {
		let r1, r2, m;
		if (utils.isEmpty(arg1)) {
			arg1 = 0;
		}
		if (utils.isEmpty(arg2)) {
			arg2 = 0;
		}
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2));
		return (utils.accMul(arg1, m) + utils.accMul(arg2, m)) / m;
	},
	/**
	 * 减法函数，用来得到精确的减法结果
	 * @param arg1
	 * @param arg2
	 * @returns {string}
	 */
	accSubtr: (arg1, arg2) => {
		let r1, r2, m, n;
		if (utils.isEmpty(arg1)) {
			arg1 = 0;
		}
		if (utils.isEmpty(arg2)) {
			arg2 = 0;
		}
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2));
		//动态控制精度长度
		n = (r1 >= r2) ? r1 : r2;
		return ((arg1 * m - arg2 * m) / m).toFixed(n);
	},
	/**
	 * 乘法函数，用来得到精确的乘法结果
	 * @param arg1
	 * @param arg2
	 * @returns {number}
	 */
	accMul: (arg1, arg2) => {
		if (utils.isEmpty(arg1) || utils.isEmpty(arg2)) {
			return 0;
		}
		let m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split(".")[1].length
		} catch (e) {
		}
		try {
			m += s2.split(".")[1].length
		} catch (e) {
		}
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
	},
	accMul2Fixed: (arg1, arg2, toFixed) => {
		let value = utils.accMul(arg1, arg2);
		if (String(value).indexOf('.') !== -1) {
			value = value.toFixed(toFixed);
		}
		return value;
	},
	accMul4Ceil: (arg1, arg2, toFixed) => {
		let value = utils.accMul2Fixed(arg1, arg2, toFixed);
		return Math.ceil(value);
	},
	/**
	 * 除法函数，用来得到精确的除法结果
	 * @param arg1
	 * @param arg2
	 * @returns {number}
	 */
	accDiv: (arg1, arg2) => {
		if (utils.isEmpty(arg1)) {
			arg1 = 0;
		}
		if (utils.isEmpty(arg2)) {
			arg2 = 0;
		}
		let t1 = 0,
			t2 = 0,
			r1, r2;
		try {
			t1 = arg1.toString().split(".")[1].length
		} catch (e) {
		}
		try {
			t2 = arg2.toString().split(".")[1].length
		} catch (e) {
		}
		r1 = Number(arg1.toString().replace(".", ""));
		r2 = Number(arg2.toString().replace(".", ""));
		return (r1 / r2) * Math.pow(10, t2 - t1);
	},
	accDiv2Fixed: (arg1, arg2, toFixed) => {
		let value = utils.accDiv(arg1, arg2);
		if (String(value).indexOf('.') !== -1) {
			value = value.toFixed(toFixed);
		}
		return value;
	},
	accDiv4Ceil: (arg1, arg2, toFixed) => {
		let value = utils.accDiv2Fixed(arg1, arg2, toFixed);
		return Math.ceil(value);
	},
	getScaleResult(x1, y1, x2) {
		x1 = typeof x1 === "undefined" ? 0 : Number(x1);
		y1 = typeof y1 === "undefined" ? 0 : Number(y1);
		x2 = typeof x2 === "undefined" ? 0 : Number(x2);
		let result = utils.accMul(x1, x2);
		if (y1 === 0) {
			return 0;
		}
		return Number(utils.accDiv(result, y1).toFixed(0));
	},
	/**
	 * 获取地址栏参数
	 * @param name
	 * @returns {string | null}
	 */
	getUrlKey(name) {
		return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [ , "" ])[1].replace(/\+/g, '%20')) || null
	},
	/**
	 * string格式化
	 * @param formatted {0}-{1}
	 * @param args ['A', 'B']
	 * @returns {*}
	 */
	stringFormat(formatted, args) {
		for (let i = 0; i < args.length; i++) {
			let regexp = new RegExp('\\{' + i + '\\}', 'gi');
			formatted = String(formatted).replace(regexp, args[i])
		}
		return formatted;
	},
	getBrowserInfo() {
		let userAgent = navigator.userAgent;
		let browser = {
			trident: userAgent.indexOf('Trident') > -1, //IE内核
			presto: userAgent.indexOf('Presto') > -1, //opera内核
			webKit: userAgent.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
			gecko: userAgent.indexOf('Gecko') > -1 && userAgent.indexOf('KHTML') === -1,//火狐内核
			mobile: !!userAgent.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
			ios: !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android: userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1, //android终端
			iPhone: userAgent.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
			iPad: userAgent.indexOf('iPad') > -1, //是否iPad
			webApp: userAgent.indexOf('Safari') === -1, //是否web应该程序，没有头部与底部
			weixin: userAgent.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
			qq: userAgent.match(/\sQQ/i) === " qq", //是否QQ
			isOpera: userAgent.indexOf("Opera") > -1, //判断是否Opera浏览器
			isIE: userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera, //判断是否IE浏览器
			isEdge: userAgent.indexOf("Edge") > -1, //判断是否IE的Edge浏览器
			isFirefox: userAgent.indexOf("Firefox") > -1, //判断是否Firefox浏览器
			isSafari: userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1, //判断是否Safari浏览器
			isChrome: userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1, //判断是否Chrome浏览器
		};
		if (browser.trident) {
			let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
			reIE.test(userAgent);
			browser.IEVersion = parseFloat(RegExp["$1"]);
		}
		return browser;
	},
	getBrowserType() {
		let info = utils.getBrowserInfo();
		if (info.mobile) {
			return info.android ? 'Android' : (info.ios ? 'IOS' : '未知');
		} else if (info.trident) {
			if (info.IEVersion > 7) {
				return 'IE' + info.IEVersion;
			} else {
				return 'IE';
			}
		} else {
			if (info.isOpera) {
				return 'Opera';
			} else if (info.isFirefox) {
				return 'Firefox';
			} else if (info.isSafari) {
				return 'Safari';
			} else if (info.isEdge) {
				return 'Edge';
			} else if (info.isChrome) {
				return 'Chrome';
			} else {
				return '未知';
			}
		}
	},
	replaceTag(route) {
		let title = route.meta.title;
		if (utils.isNotEmpty(route.meta.appendTag)) {
			let value = route.query[route.meta.appendTag];
			if (utils.isNotEmpty(value)) {
				title = title + '-' + value
			}
		}
		if (utils.isNotEmpty(route.meta.prependTag)) {
			let value = route.query[route.meta.prependTag];
			if (utils.isNotEmpty(value)) {
				title = value + '-' + title
			}
		}
		if (utils.isNotEmpty(route.meta.replaceTag)) {
			let value = route.query[route.meta.replaceTag];
			if (!utils.isNotEmpty(value)) {
				value = '';
			}
			title = utils.stringFormat(title, [ value ]);
		}
		return title;
	},
	setProjectHistory(projectHistory, route, historyId) {
		let object = {};
		object[historyId] = {
			path: route.path,
			query: route.query,
		};
		let history = $.extend({}, projectHistory, object);
		store.commit('setProjectHistory', history);
	},
	/**
	 * 数组去重
	 * @param arr 基本数组 如：[1, 2, 3]
	 * @returns {[]}
	 */
	arrayUnique(arr) {
		let res = [];
		let obj = {};
		for (let i = 0; i < arr.length; i++) {
			if (!obj[arr[i]]) {
				obj[arr[i]] = 1;
				res.push(arr[i]);
			}
		}
		return res;
	},
	getSpanOpt(sectionList, field, continuousField) {
		let sections = sectionList.map(item => item[field]);
		let uniqueSections = utils.arrayUnique(sections);
		let spanObj = {}, spanIndex = [];
		for (let i = 0; i < uniqueSections.length; i++) {
			let obj = uniqueSections[i];
			let filter = sectionList.filter(item => item[field] === obj);
			if (continuousField) {
				let fieldList = filter.map(item => item[continuousField]);
				let newFieldList = fieldList.reduce((arr, value) => {
					if (arr.length && (value - arr[0][0]) === 1) {
						arr[0].unshift(value);
					} else {
						arr.unshift([ value ]);
					}
					return arr;
				}, []).reverse().map(a => a.reverse());
				if (newFieldList.length === 1) {
					let index = sectionList.findIndex(item => item[field] === obj);
					spanObj[obj + '_' + sectionList[index][continuousField]] = filter.length;
					spanIndex.push(index);
				} else {
					newFieldList.forEach(arr => {
						let index = sectionList.findIndex(item => item[continuousField] === arr[0]);
						spanObj[obj + '_' + sectionList[index][continuousField]] = arr.length;
						spanIndex.push(index);
					});
				}
			} else {
				spanObj[obj] = filter.length;
				let index = sectionList.findIndex(item => item[field] === obj);
				spanIndex.push(index);
			}
		}
		return {
			obj: spanObj,
			index: spanIndex,
		};
	},
	getDpi() {
		let arrDPI = [];
		if (window.screen.deviceXDPI !== undefined) {
			arrDPI[0] = window.screen.deviceXDPI;
			arrDPI[1] = window.screen.deviceYDPI;
		} else {
			let tmpNode = document.createElement("DIV");
			tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
			document.body.appendChild(tmpNode);
			arrDPI[0] = parseInt(tmpNode.offsetWidth);
			arrDPI[1] = parseInt(tmpNode.offsetHeight);
			tmpNode.parentNode.removeChild(tmpNode);
		}
		return arrDPI;
	},
	getA4Size(margin) {
		if (!margin) {
			margin = 0;
		}
		let inchWidth = (210 - margin) / 25.4;
		let inchHeght = (297 - margin) / 25.4;
		return {
			width: Math.round(inchWidth * utils.getDpi()[0]),
			height: Math.round(inchHeght * utils.getDpi()[1]),
		}
	},
	getPositionName(position_type) {
		if (position_type === 'zf') {
			return '左幅';
		}
		if (position_type === 'yf') {
			return '右幅';
		}
		if (position_type === 'qf') {
			return '全幅';
		}
		return '';
	},
	//查看文件
	readFile(url, officePreviewType) {
		let openUrl = window.configs.viewPrefix + this.transFilePreviewUrl(url);
		// let openUrl = window.configs.viewPrefix + url;
		if (utils.isNotEmpty(officePreviewType)) {
			openUrl = `${ openUrl }&officePreviewType=${ officePreviewType }`;
		}
		window.open(openUrl);
	},
	//保留小数点后两位
	keepTwoDecimalFull(num) {
		let result = parseFloat(num);
		if (isNaN(result)) {
			// alert('传递参数错误，请检查！');
			return "";
		}
		return result.toFixed(2);
	},
	getStrLen(val) {
		if (val.match(/[^\x00-\xff]/ig) != null) {
			return 2;
		} else {
			return 1;
		}
	},
	getByteLen(val) {
		let len = 0;
		for (let i = 0; i < val.length; i++) {
			let a = val.charAt(i);
			if (a.match(/[^\x00-\xff]/ig) != null) {
				len += 2;
			} else {
				len += 1;
			}
		}
		return len;
	},
	/**
	 * 拆分数组
	 * @param array 原数组
	 * @param itemNum 数组内对象个数
	 * @returns {[]} 拆分后数组
	 */
	splitArray(array, itemNum) {
		// 声明数组
		const splitArr = [];
		array.forEach((item, index) => {
			// 计算该元素为第几个素组内
			const page = Math.floor(index / itemNum);
			// 判断是否存在
			if (!splitArr[page]) {
				splitArr[page] = [];
			}
			splitArr[page].push(item);
		});
		return splitArr;
	},
	objectToQueryString(obj) {
		return Object.keys(obj).map(key => {
			return `${ encodeURIComponent(key) }=${ encodeURIComponent(obj[key]) }`;
		}).join('&');
	},
	prefixInteger(num, length) {
		return (Array(length).join(0) + num).slice(-length);
	},
	//文件预览URL转换，可以使用base64或者是encodeURIComponent
	transFilePreviewUrl(url) {
		let u = url.toLowerCase().trim()
		if (u.substring(0, 7) === 'http://' || u.substring(0, 8) === 'https://' || u.substring(0, 6) === 'ftp://') {
			//不需要处理
		} else if (u.substring(0, 1) === '/') {
			//Linux下的文件路径
			url = 'file://' + url;
		} else {
			//window下的文件路径
			url = 'file:///' + url.replaceAll("\\", "\/");
		}
		return encodeURIComponent(Base64.encode(url));
	},
	/**
	 * 数字金额大写转换
	 */
	digitUppercase(n) {
		let fraction = [ '角', '分' ];
		let digit = [
			'零', '壹', '贰', '叁', '肆',
			'伍', '陆', '柒', '捌', '玖'
		];
		let unit = [
			[ '元', '万', '亿' ],
			[ '', '拾', '佰', '仟' ]
		];
		let head = n < 0 ? '欠' : '';
		n = Math.abs(n);
		let s = '';
		for (let i = 0; i < fraction.length; i++) {
			s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
		}
		s = s || '整';
		n = Math.floor(n);
		for (let i = 0; i < unit[0].length && n > 0; i++) {
			let p = '';
			for (let j = 0; j < unit[1].length && n > 0; j++) {
				p = digit[n % 10] + unit[1][j] + p;
				n = Math.floor(n / 10);
			}
			s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
		}
		return head + s.replace(/(零.)*零元/, '元')
		.replace(/(零.)+/g, '零')
		.replace(/^整$/, '零元整');
	},
};
export default utils;
